const jwt = require('jsonwebtoken');

const { PUBLIC_KEY} = require('../app/config');
const errorType = require('../constants/error-types')
const service = require('../service/user.service');
const md5password = require('../utils/password-handle');

const verifyLogin = async (ctx, next) => {
  //1.判断前端输入的账号密码是否为空
  const { account, password } = ctx.request.body;
  if (!account || !password) {
    const error = new Error(errorType.ACCOUNT_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }
  //2.判断账号是否是已注册的，如果没有注册则抛出异常
  const result = await service.getUserByAccount(account);
  const user = result[0];
  if (!user) {
    const error = new Error(errorType.USER_DOES_NOT_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  //3.判断输入的账号和数据库的是否相同
  if (md5password(password) != user.password) {
    const error = new Error(errorType.WRONG_PASSWORD);
    return ctx.app.emit('error',error,ctx)
  }
  ctx.user = user;
  await next()
}

const verifyAuth = async (ctx,next)=>{
  const authorization = ctx.headers.authorization;
  const token = authorization.replace('Bearer ','')

  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms:['RS256']
    });
    ctx.user = result;
    await next();
  } catch (err) {
    const error = new Error(errorType.UNAUTHORIZATION);
    ctx.app.emit('error',error,ctx);
  }
}

module.exports = {
  verifyLogin,
  verifyAuth
}